package com.fingard.dsp.bank.directbank.icbc02;

import com.alibaba.fastjson.JSON;
import com.fingard.net.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.fingard.FGBiz;
import com.fingard.constant.DecimalFormat2;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptMapping;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.helpers.HelperResp;
import com.fingard.dsp.bank.helpers.ReceiptFileSaveHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceiptDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 工行电子回单
 *
 * @author Cruise
 * @version 1.0
 * @date created in 2018/1/29
 * @modify 2018/3/20
 */
public class ICBC02Receipt extends ICBC02Base implements IReceipt {
    @Override
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        if ("receiptXml".equals(getBankConfig().getValueAsString("receiptType"))) {
            return qryReceiptXml(p_reqReceipt);
        } else {
            if (getBankConfig().getValueAsBool("isHeadVersion")) {
                return qryReceiptFtpByHeadVersion(p_reqReceipt);
            }
            return qryReceiptFtp(p_reqReceipt);
        }
    }

    /**
     *    总行标准下载回单 。文件名
     *   1001900006FFFFF_20190103_2_00000.zip
     *   固定编号_YYYYMMDD_本日回单总数_本日第X个回单文件
     */
    private RetAtsReceipt qryReceiptFtpByHeadVersion(ReqQryReceipt p_reqReceipt) throws Exception {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        retAts.respCode = "0";
        String tmpRespCode = "";
        String tmpRespInfo = "";
        String uploadType=SmbFileUtil.getUploadType();
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int intFromForWhile = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int intToForWhile = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            boolean receiptUploadShared = this.getBankConfig().getValueAsBool("receiptUploadShared");
            StringBuilder json = new StringBuilder();
            if(getBankConfig().getValueAsBool("receiptPushHasTenantId")){
                json.append("tenantId="+FGBiz.dspCenter.dspSet.tenant+"&transType=downloadreceipt&data={\"rows\":[");
            }else{
                json.append("transType=downloadreceipt&data={\"rows\":[");
            }

            FtpSet ftpSet = bankFront.getFtpSet("receipt");
            if (ftpSet != null) {
                String localReceiptPath = bankFront.bankReceiptMainDir;
            if("".equals(localReceiptPath)){
                retAts.respCode = "-1";
                retAts.respInfo = "Bankfront.xml 中ICBC02未配置本地保存回单路径bankReceiptMainDir";
                WriteBankLogLn("Bankfront.xml 中ICBC02未配置本地保存回单路径bankReceiptMainDir");
                return retAts;
            }
                WriteBankLogLn("本地保存回单路径:" + localReceiptPath);
                //FTP下载回单
              // D:\Jyworkspace\DSP\trunk\Rceipt\2019\0102 \1001900006FFFFF_20181226_3_00000.zip;

                ReceiptFileSaveHelper saveHelper = new ReceiptFileSaveHelper(this);
                if (!saveHelper.checkSet(this.sbLog, "102")) {
                    retAts.respCode = "-1";
                    retAts.respInfo = sbLog.toString();
                    retAts.writeRetToATS();
                    return retAts;
                }
                int tmpFileCount = 0;
                boolean isAllRight = true;
                while (intFromForWhile <= intToForWhile) {
                    String currentDate = Format.Date8Format.format(tmpCalendarFrom.getTime());
                    Date fromDateStep = tmpCalendarFrom.getTime();
                    tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                    //tmpIntFrom = Integer.parseInt(fromdate);
                    //加1天，后面不能再用tmpIntFrom
                    intFromForWhile = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    if("sftp".equals(ftpSet.ftpType)){
                    	downFromSftp(fromDateStep, localReceiptPath,ftpSet);
                    }else{
                    	downFromFtp(fromDateStep, localReceiptPath,ftpSet);
                    }

                    String destPath= localReceiptPath + File.separator + currentDate.substring(0, 4) + File.separator + currentDate.substring(4, 8);

                    WriteBankLogLn("开始遍历：" + destPath);
                    String[] filenames = FileHelper.listFiles(destPath);
                    //遍历日期内的文件
                    if (filenames == null) {
                        continue;
                    }
                    List<String> list = Arrays.asList(filenames);
                    for (String filename : list) {
                        String receiptFile = "";
                        if (filename.endsWith("zip")) {
                            String dirName = filename.substring(0, filename.lastIndexOf("."));
                            if (list.contains(dirName)) {
                                continue;
                            }
                            WriteBankLogLn("开始解压文件" + filename);
                            ZipHelper.unzipFile(destPath + File.separator + filename, destPath);
                            //解压后的文件夹
                            receiptFile = destPath + File.separator + dirName;
                        } else {
                            receiptFile=destPath+File.separator + filename;
                        }
                        String[] files  = FileHelper.listFiles(receiptFile);
                        ArrayList<String> listToDelete = new ArrayList<String>();
                        if (files == null) {
                            WriteBankLogLn("解压后文件夹" + receiptFile + "下为空");
                            continue;
                        }
                            for (String file : files) {
                                if ((file.endsWith(".PDF") || file.endsWith(".pdf"))  && file.startsWith(p_reqReceipt.actNum)) {
                                    //1202027719900235368_20181225_18359000031.PDF
                                    String localRecipt = receiptFile + File.separator + file;

                                    String[] filenameSpliter = file.split("_");
                                    if (filenameSpliter.length < 3) {
                                        WriteBankLogLn("回单文件:" + file + "文件名错误");
                                        continue;
                                    }
                                    String receiptNo = filenameSpliter[0] + "R" + filenameSpliter[2].substring(0,11);
                                    ReceiptMapping eachRcptMp = new ReceiptMapping();
                                    eachRcptMp.busRef = receiptNo;
                                    String otherBusRef = "";
                                    int idxDot = filenameSpliter[2].lastIndexOf(".");
                                    if(idxDot>0){
                                    	otherBusRef = filenameSpliter[2].substring(0, idxDot);
                                    }else{
                                    	otherBusRef = filenameSpliter[2];
                                    }
                                    eachRcptMp.addOtherBusRef(otherBusRef, otherBusRef);
                                    eachRcptMp.bank = "102";
                                    eachRcptMp.setBusDate(fromDateStep);
                                    eachRcptMp.ownAct = p_reqReceipt.actNum;
                                    eachRcptMp.amount = new BigDecimal("0.00");
                                    eachRcptMp.keyName = "receiptNo";
                                    eachRcptMp.receiptNo = receiptNo;
                                    eachRcptMp.srcFile = StringHelper.getFileName(localRecipt);
                                    //HelperResp saveResp = saveHelper.saveFile(this.reqHeader, FileType.receipt, localReceiptPath, receiptNo, fromDateStep, p_reqReceipt.actNum);
                                    if (receiptUploadShared) {
                                        int result = -1;
                                        String ftpFilePath="";
                                        String AtsFilePath = "";
                                        String tmpByDate = Format.Date8Format.format(new Date());
                                        tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                        if (new File(localRecipt).exists()) {
                                            if(!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)){
                                              if("smb".equals(uploadType)) {
                                                  WriteBankLogLn("正在上传文件至共享目录1:" + tmpByDate + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                  result = SmbFileUtil.smbUploading(localRecipt, tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                                  AtsFilePath = tmpByDate + eachRcptMp.srcFile;
                                              }else if("localhost".equals(uploadType)){
                                                  String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                                  WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                                  result = FileHelper.copyFile(localRecipt, shareDir + tmpByDate + file);
                                                  AtsFilePath = tmpByDate + eachRcptMp.srcFile;
                                              } else{
                                                    tmpByDate =tmpByDate.replaceAll(reqHeader.bankCode + "/","");
                                                    WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                    Map<String,String> map = FormSubmit.fileUpload
                                                            (FGBiz.dspCenter.dspSet.receiptShareDir,p_reqReceipt.actNum,localRecipt,tmpByDate, eachRcptMp.srcFile,getCharset());
                                                    WriteBankLogStep3(JSON.toJSONString(map));
                                                    if(map.keySet().size()!=0){
                                                        result = Integer.valueOf(map.get("respCode"));
                                                        tmpByDate =map.get("remotePath");
                                                        AtsFilePath = tmpByDate;
                                                    }else{
                                                        result = -1;
                                                    }
                                                }
                                            }else {
                                                //ftp服务器
                                                FtpSet ftpSet3 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet3.upDir);
                                                //上传ftp服务器的地址
                                                AtsFilePath=tmpByDate+new File(localRecipt).getName();
                                                ftpFilePath = StringHelper.trimEndFileSp(ftpSet3.upDir) + "/" +AtsFilePath;
                                                WriteBankLogLn("开始将回单"+localRecipt+"上传至"+ftpFilePath);
                                                //上传至ftp
                                                result = FtpUtil.ftpUploading(ftpSet3, localRecipt, ftpFilePath);
                                            }
                                        }
                                        if (result == 0 || result == 1) {
                                            if (result == 0) {
                                                WriteBankLogLn("文件上传成功");
                                            } else {
                                                WriteBankLogLn("文件已存在共享目录无需重复上传");
                                            }
                                            //推送数据给ATS处理
                                            json.append("{");
                                            json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                            json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                            json.append("\"receiptCode\":\"" + receiptNo + "\",");
                                            json.append("\"receiptType\":\"" + "" + "\",");
                                            json.append("\"receiptState\":\"" + "" + "\",");
                                            json.append("\"oppActName\":\"" + "\",");
                                            json.append("\"oppActNum\":\"" + "" + "\",");
                                            json.append("\"moneyway\":\"" + "\",");
                                            json.append("\"amount\":\"" + "" + "\",");
                                            json.append("\"tranSeqNo\":\"" + filenameSpliter[2].substring(0, 11) + "\",");
                                            json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                            json.append("\"tranDate\":\"" + Format.Date10Format.format(fromDateStep) + "\",");
                                            json.append("\"filePath\":\"" + AtsFilePath + "\",");//回单文件仓库存储路径
                                            json.append("\"fileType\":\"1\"");
                                            json.append("},");
                                        } else {
                                            retAts.respCode = "-1";
                                            retAts.respInfo = "上传文件至共享目录失败，请检查共享目录配置是否正确";
                                            break;
                                        }
                                    } else {
                                        HelperResp saveResp = saveHelper.saveByRcptMap(reqHeader, eachRcptMp, localRecipt);
                                        WriteBankLogLn(saveResp.sbMsg);
                                        if (saveResp.isCompleted) {
                                            tmpFileCount++;
                                            listToDelete.add(localRecipt);
                                        } else if (ConnState.FAIL.equals(saveResp.connState)) {
                                            WriteBankLogLn("连接服务器失败，终止本次推送");
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "连接服务器失败，终止本次推送";
                                            isAllRight = false;
                                            break;
                                        } else if (ConnState.CLASS_NOT_FOUND.equals(saveResp.connState)) {
                                            WriteBankLogLn(ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送");
                                            tmpRespCode = "-1";
                                            tmpRespInfo = ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送";
                                            isAllRight = false;
                                            break;
                                        }
                                    }
                                }
                            }
                            int delCount = 0;
                            for (String delFile : listToDelete) {
                                try {
                                    if(FileHelper.deleteFileIfExists(delFile)){
                                    	delCount++;
                                    }
                                } catch (Exception ex) {
                                    WriteBankLogLn(ex);
                                }
                            }
                            WriteBankLogLn("成功删除了" + delCount + "个文件");
                            if (!isAllRight) {
                                break;
                            }
                    }
                }

                if (isAllRight) {
                    retAts.respCode = "0";
                    retAts.respInfo = "成功保存了" + tmpFileCount + "个文件";
                    WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
                }
            } else {
                retAts.respCode = "0";
                retAts.respInfo = "未找到回单下载的ftp设置";
            }

            json.append("]}");
            if (receiptUploadShared && json.toString().contains("receiptCode")) {
                String[] data ;
                String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                if("nbGateway".equals(receiptPushType)) {
                    WriteBankLogLn("3.推送给网关的数据" + json.toString());
                    data= FormSubmit.receiptInfoSend(json.toString(),this);
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到网关成功,请查看数据");
                    } else {
                        WriteBankLogLn("推送数据到网关失败");
                    }
                }else{
                    WriteBankLogLn("3.推送给ATS的数据" + json.toString());
                    data = sendToATS(json.toString());
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到ATS成功,请查看数据");
                    } else {
                        WriteBankLogLn("推送数据到ATS失败");
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetToATS();
        return retAts;
    }

    private void downFromSftp(Date pDate, String localReceiptPath, FtpSet ftpSet)  throws Exception {
    	SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
        //从FTP下载回单
        FtpReceiver ftpReceiver = null;
        try {
            if (getBankConfig().getValueAsBool("isSftpBySSH")) {
            	sftpPortClient.connectBySSH();
        	}else{
        		sftpPortClient.connect();
        	}
            
        	ftpReceiver = sftpPortClient.listFiles(ftpSet.downDir);
            WriteBankLogLn("开始从【" + ftpSet.serverIP + ":" + ftpSet.port + ftpSet.downDir + "】下载回单文件");
            if (ftpReceiver.isCompleted) {
            	String[] filesArray = ftpReceiver.connMsg.split(",");
            	String matchDate = Format.Date8Format.format(pDate);
                for (String receiptZip : filesArray) {
                	if(receiptZip.indexOf(matchDate)<0){
                		continue;
                	}
                	ftpReceiver = sftpPortClient.downloadFile("", receiptZip, localReceiptPath + File.separator + receiptZip);
                    if (ftpReceiver.isCompleted) {
                        WriteBankLogLn("成功下载回单文件:" + receiptZip);
                        //下载成功后删除ftp文件
                        //ftpReceiver = sftpPortClient.deleteFile(ftpSet.downDir, receiptZip);
                        //if (ftpReceiver.isCompleted) {
                        //    WriteBankLogLn("成功删除FTP端回单文件:" + receiptZip);
                        //} else {
                        //    WriteBankLogLn(receiptZip + "回单文件删除失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                        //}
                    } else {
                        WriteBankLogLn(receiptZip + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                    }
                }
            } else {
                WriteBankLogLn("【" + ftpSet.serverIP + ":" + ftpSet.port + ftpSet.downDir + "】"+ftpReceiver.connMsg);
            }
            String[] files = FileHelper.listFiles(localReceiptPath);
            for (String filename : files) {
                String[] nameSpliter = filename.split("_");
                if (nameSpliter.length >= 4) {
                    String srcPath = localReceiptPath + File.separator + filename;
                    File srcFile = new File(srcPath);
                    //1001900006FFFFF_20190103_2_00001.zip
                    if (srcFile.exists() && srcFile.isFile()) {
                        String destPath = localReceiptPath + File.separator + nameSpliter[1].substring(0, 4) + File.separator + nameSpliter[1].substring(4, 8) +File.separator +filename;
                        File destFile = new File(destPath);
                        try {
                            FileHelper.moveFile(srcFile, destFile);
                            WriteBankLogLn("保存回单文件至:" + destPath);
                        } catch (Exception e) {
                            WriteBankLogLn("回单文件" + srcFile + "复制失败");
                        }
                    }
                }
            }
        } finally {
        	sftpPortClient.disconnect();
        }

    }

    private void downFromFtp(Date pDate, String localReceiptPath, FtpSet ftpSet)  throws Exception {
        FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
        //从FTP下载回单
        FtpReceiver ftpReceiver = null;
        try {
            ftpPtClient.setLocalPassiveMode();
            ftpPtClient.connect();
            ftpPtClient.list(ftpSet.downDir, false);
            WriteBankLogLn("开始从【" + ftpSet.serverIP + ":" + ftpSet.port + ftpSet.downDir + "】下载回单文件");
            if (ftpPtClient.arFiles.size() > 0) {
            	String matchDate = Format.Date8Format.format(pDate);
                for (String receiptZip : ftpPtClient.arFiles) {
                	if(receiptZip.indexOf(matchDate)<0){
                		continue;
                	}
                    ftpReceiver = ftpPtClient.downloadFile(receiptZip, localReceiptPath + File.separator + receiptZip.substring(receiptZip.lastIndexOf("/") + 1));
                    if (ftpReceiver.isCompleted) {
                        WriteBankLogLn("成功下载回单文件:" + receiptZip);
                        //下载成功后删除ftp文件
                        ftpReceiver = ftpPtClient.deleteFile(receiptZip);
                        if (ftpReceiver.isCompleted) {
                            WriteBankLogLn("成功删除FTP端回单文件:" + receiptZip);
                        } else {
                            WriteBankLogLn(receiptZip + "回单文件删除失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                        }
                    } else {
                        WriteBankLogLn(receiptZip + "回单文件下载失败:" + ftpReceiver.connMsg + "+" + ftpReceiver.connState);
                    }
                }
            } else {
                WriteBankLogLn("【" + ftpSet.serverIP + ":" + ftpSet.port + ftpSet.downDir + "】不存在文件");
            }
            String[] files = FileHelper.listFiles(localReceiptPath);
            for (String filename : files) {
                String[] nameSpliter = filename.split("_");
                if (nameSpliter.length >= 4) {
                    String srcPath = localReceiptPath + File.separator + filename;
                    File srcFile = new File(srcPath);
                    //1001900006FFFFF_20190103_2_00001.zip
                    if (srcFile.exists() && srcFile.isFile()) {
                        String destPath = localReceiptPath + File.separator + nameSpliter[1].substring(0, 4) + File.separator + nameSpliter[1].substring(4, 8) +File.separator +filename;
                        File destFile = new File(destPath);
                        try {
                            FileHelper.moveFile(srcFile, destFile);
                            WriteBankLogLn("保存回单文件至:" + destPath);
                        } catch (Exception e) {
                            WriteBankLogLn("回单文件" + srcFile + "复制失败");
                        }
                    }
                }
            }
        } finally {
            ftpPtClient.disconnect();
        }

    }


    private RetAtsReceipt qryReceiptFtp(ReqQryReceipt p_reqReceipt) throws Exception {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        retAts.respCode = "0";
        FtpPortClient ftpPtClient = null;
        String uploadType=SmbFileUtil.getUploadType();
        String tmpRespCode = "";
        String tmpRespInfo = "";

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            StringBuilder json = new StringBuilder();
            if(getBankConfig().getValueAsBool("receiptPushHasTenantId")){
                json.append("tenantId="+FGBiz.dspCenter.dspSet.tenant+"&transType=downloadreceipt&data={\"rows\":[");
            }else{
                json.append("transType=downloadreceipt&data={\"rows\":[");
            }
            boolean receiptUploadShared = this.getBankConfig().getValueAsBool("receiptUploadShared");
            FtpSet ftpSet = bankFront.getFtpSet("receipt");
            if (ftpSet != null) {
                ftpPtClient = new FtpPortClient(ftpSet);

                DataFileHelper dFileHelper = new DataFileHelper(this);
                while (tmpIntFrom <= tmpIntTo) {
                    int intFromStep = tmpIntFrom;
                    Date fromDateStep = tmpCalendarFrom.getTime();
                    tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                    tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));

                    String dataFilePath = dFileHelper.getBankReceiptDataFile(fromDateStep, p_reqReceipt.actNum);
                    File dataFile = new File(dataFilePath);
                    if (dataFile.exists()) {
                        WriteBankLogLn(intFromStep + "的回单已执行过下载，如需重新获取，请删除文件" + dataFilePath);
                        retAts.respCode = "0";
                        retAts.respInfo = intFromStep + "的回单已执行过下载";
                        continue;
                    }

                    WriteBankLogLn("开始执行" + intFromStep + "的回单文件下载");
                    String downFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + intFromStep + ".zip";
                    String localDir = getTempFileDirectory();
                    String localSavePath = localDir + File.separator + intFromStep + ".zip";
                    WriteBankLogLn("FTP下载地址: [" + ftpSet.serverIP + ":" + ftpSet.port + "].");
                    WriteBankLogLn("开始下载服务器文件- [" + downFilePath + "],至本地- [" + localSavePath + "].");

                    String tmpDecompressDir = getTempFileDirectory();

                    boolean isDownFileSucc = false;
                    //File unzipSucc = new File(tmpDecompressDir+"_success_"+intFromStep);
                    FtpReceiver tmpReceiver = null;
                    //if(!unzipSucc.exists()){
                    tmpReceiver = ftpPtClient.downloadFile(downFilePath, localSavePath);
                    //tmpReceiver = new FtpReceiver();
                    //FtpUtil.downloadFtpFile(ftpSet.serverIP, ftpSet.userName, ftpSet.userPassword, ftpSet.port, ftpSet.downDir, localDir, intFromStep + ".zip");
                    //test
                    //tmpReceiver.connState = "";
                    //tmpReceiver.isCompleted = true;
                    //localSavePath = "D:\\svn3\\dsplatest\\tempfile\\20180103.zip";
                    //test
                    WriteBankLogLn(ftpPtClient.sbLog);
                    if (tmpReceiver.isCompleted) {
                        WriteBankLogLn("文件下载已完成，开始解压...");

                        WriteBankLogLn("解压至：[" + tmpDecompressDir + "]");
                        ZipHelper.unzipFile(localSavePath, tmpDecompressDir);
                        WriteBankLogLn("文件解压已完成.");
                        File depressDir = new File(tmpDecompressDir);
                        if (depressDir.exists()) {
                            File[] deFiles = depressDir.listFiles();
                            if (deFiles != null && deFiles.length > 0) {
                                //if(!unzipSucc.exists()){
                                //	unzipSucc.mkdirs();
                                //}
                                isDownFileSucc = true;
                            } else {
                                tmpReceiver.connMsg += "解压后文件夹" + tmpDecompressDir + "下为空";
                            }
                        } else {
                            tmpReceiver.connMsg += "解压后文件夹" + tmpDecompressDir + "不存在";
                        }
                    } else {
                        WriteBankLogLn(tmpReceiver.connMsg);
                        retAts.respInfo = tmpReceiver.connMsg;
                    }
                    //}else{
                    //	WriteBankLogLn("已存在解压文件夹"+tmpDecompressDir+"，如需重新下载，请删除，并删除"+tmpDecompressDir+"_success_"+intFromStep);
                    //	isDownFileSucc = true;
                    //}

                    if (isDownFileSucc) {
                    	retAts.respCode = "0";
                        tmpRespCode = "0";

                        File receiptDir = new File(tmpDecompressDir + File.separator + intFromStep);
                        if (receiptDir.exists()) {
                            ReceiptFileSaveHelper saveHelper = new ReceiptFileSaveHelper(this);
                            if (!saveHelper.checkSet(this.sbLog, "102")) {
                                retAts.respCode = "-1";
                                retAts.respInfo = sbLog.toString();
                                retAts.writeRetToATS();
                                return retAts;
                            }

                            int tmpFileCount = 0;
                            //ArrayList<String> listToDelete = new ArrayList<String>();
                            ArrayList<String> unknowRcptType = new ArrayList<String>();

                            File[] receiptFiles = receiptDir.listFiles();
                            
                            
                            for (File receiptFile : receiptFiles) {
                                String eachName = receiptFile.getName();
                                if (eachName.toLowerCase().endsWith(".html") && eachName.contains(p_reqReceipt.actNum)) {
                                    // 解析HTML文件内容读取回单编号关联关系
                                    String receiptHtml = FileHelper.readFileText(receiptFile.getAbsolutePath(), getCharset());
                                    Document receiptDoc = (Document) Jsoup.parse(receiptHtml);

                                    Element receiptNoTable = receiptDoc.select("table").last();
                                    Elements receiptLinks = receiptNoTable.getElementsByTag("a");
                                    boolean isAllRight = true;
                                    for (Element receiptLink : receiptLinks) {
                                        String receiptRelativePath = receiptLink.attr("href");
                                        String receiptNo = receiptLink.text();
                                        ReceiptMapping eachRcptMp = new ReceiptMapping();
                                        RetAtsReceiptDetail rcptDt = new RetAtsReceiptDetail();
                                        String localReceiptPath = receiptDir + File.separator + receiptRelativePath.replace("/", File.separator);
                                        
                                        String xmlDataPath = localReceiptPath.replace(".pdf", ".xml");
                                        File xmldfile = new File(xmlDataPath);
                                        if(xmldfile.exists()){
                                        	String dataContext = FileHelper.readToString(xmldfile, this.getBankConfig().getCharset("gbk", "receiptXmlFile"));
                                        	XmlTextReader dataReader = new XmlTextReader(dataContext);
                                        	String drcrf = dataReader.getSimpleText("drcrf");
                                        	if("1".equals(drcrf)){
                                        		eachRcptMp.moneyWay = "1";
                                        		rcptDt.oppActName = dataReader.getSimpleText("craccname");
                                        		rcptDt.oppActNum = dataReader.getSimpleText("craccno");
                                        	}else if("2".equals(drcrf)){
                                        		eachRcptMp.moneyWay = "2";
                                        		rcptDt.oppActName = dataReader.getSimpleText("draccname");
                                        		rcptDt.oppActNum = dataReader.getSimpleText("draccno");
                                        	}
                                        	String amount = dataReader.getSimpleText("amount");
                                        	rcptDt.amount = amount;
                                        	if(StringHelper.hasAnyChar(amount)){
                                        		eachRcptMp.amount = new BigDecimal(amount);
                                        	}
                                        	rcptDt.summary = dataReader.getSimpleText("f_1");
                                        }else{
                                        	WriteBankLogLn("回单编号"+receiptNo+"不存在对应的xml数据文件："+xmlDataPath);
                                        }
                                        
                                        
                                        eachRcptMp.busRef = receiptNo;
                                        eachRcptMp.bank = "102";
                                        eachRcptMp.setBusDate(fromDateStep);
                                        eachRcptMp.ownAct = p_reqReceipt.actNum;
                                        eachRcptMp.keyName = "receiptNo";
                                        eachRcptMp.receiptNo = receiptNo;
                                        eachRcptMp.srcFile = StringHelper.getFileName(localReceiptPath);
                                        //HelperResp saveResp = saveHelper.saveFile(this.reqHeader, FileType.receipt, localReceiptPath, receiptNo, fromDateStep, p_reqReceipt.actNum);
                                        
                                        rcptDt.istNbr = receiptNo + "_" + p_reqReceipt.actNum;
                                        rcptDt.receiptNo = receiptNo;
                                        rcptDt.busDate = fromDateStep;
                                        rcptDt.busRef = receiptNo;
                                        rcptDt.cur = "1";
                                        rcptDt.moneyWay = eachRcptMp.moneyWay;
                                        
                                        
                                        if (receiptUploadShared) {
                                            int result = -1;
                                            String ftpFilePath="";
                                            String filePath2="";
                                            String AtsFilePath = "";
                                            //WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            String tmpByDate = Format.Date8Format.format(new Date());
                                            tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                            if (new File(localReceiptPath).exists()) {
                                                if(!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)){
                                                   if("smb".equals(uploadType)) {
                                                       WriteBankLogLn("正在上传文件至共享目录:"  + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                       result = SmbFileUtil.smbUploading(localReceiptPath, tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                                       AtsFilePath =  eachRcptMp.srcFile;
                                                   }else if("localhost".equals(uploadType)) {
                                                       String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                                       WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                                       result = FileHelper.copyFile(localReceiptPath, shareDir + tmpByDate + eachRcptMp.srcFile);
                                                       AtsFilePath = tmpByDate + eachRcptMp.srcFile;
                                                   } else{
                                                        tmpByDate =tmpByDate.replaceAll(reqHeader.bankCode + "/","");
                                                        WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                        Map<String,String> map = FormSubmit.fileUpload
                                                                (FGBiz.dspCenter.dspSet.receiptShareDir, p_reqReceipt.actNum,localReceiptPath,tmpByDate,eachRcptMp.srcFile,getCharset());
                                                       WriteBankLogStep3(JSON.toJSONString(map));
                                                        if(map.keySet().size()!=0){
                                                            result = Integer.valueOf(map.get("respCode"));
                                                            tmpByDate =map.get("remotePath");
                                                            AtsFilePath = tmpByDate;
                                                        }else{
                                                            result = -1;
                                                        }
                                                    }
                                                }else {
                                                    //ftp服务器
                                                    FtpSet ftpSet2 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                    WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet2.upDir);
                                                    //上传ftp服务器的地址
                                                    filePath2=tmpByDate+new File(localReceiptPath).getName();
                                                    ftpFilePath = StringHelper.trimEndFileSp(ftpSet2.upDir) + "/" +filePath2;
                                                    WriteBankLogLn("开始将回单"+localReceiptPath+"上传至"+ftpFilePath);
                                                    //上传至ftp
                                                    result = FtpUtil.ftpUploading(ftpSet2, localReceiptPath, ftpFilePath);
                                                    AtsFilePath = filePath2;
                                                }
                                            }
                                            if (result == 0 || result == 1) {
                                                if (result == 0) {
                                                    WriteBankLogLn("文件上传成功");
                                                } else {
                                                    WriteBankLogLn("文件已存在共享目录无需重复上传");
                                                }
                                                //推送数据给ATS处理
                                                json.append("{");
                                                json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                                json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                                json.append("\"receiptCode\":\"" + receiptNo + "\",");
                                                json.append("\"receiptType\":\"" + "" + "\",");
                                                json.append("\"receiptState\":\"" + "" + "\",");
                                                json.append("\"oppActName\":\"" + "\",");
                                                json.append("\"oppActNum\":\"" + "" + "\",");
                                                json.append("\"moneyway\":\"" + "\",");
                                                json.append("\"amount\":\"" + eachRcptMp.amount + "\",");
                                                json.append("\"tranSeqNo\":\"" + reqHeader.transSeqID + "\",");
                                                json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                                json.append("\"tranDate\":\"" + Format.Date10Format.format(fromDateStep) + "\",");
                                                json.append("\"filePath\":\"" + AtsFilePath + "\",");//回单文件仓库存储路径
                                                json.append("\"fileType\":\"1\"");
                                                json.append("},");
                                            } else {
                                                retAts.respCode = "-1";
                                                retAts.respInfo = "上传文件至共享目录失败，请检查共享目录配置是否正确";
                                                break;
                                            }
                                        }else {
                                            HelperResp saveResp = saveHelper.saveByRcptMap(reqHeader, eachRcptMp, localReceiptPath);
                                            WriteBankLogLn(saveResp.sbMsg);
                                            if (saveResp.isCompleted) {
                                                tmpFileCount++;
                                                //listToDelete.add(localReceiptPath);
                                                File toDel = new File(localReceiptPath);
                                                WriteBankLogLn("删除文件" + toDel.getName());
                                                toDel.delete();
                                                //FileHelper.writeFile(dataFile, "文件" + receiptRelativePath + "推送成功!", getCharset());
                                            } else if (ConnState.FAIL.equals(saveResp.connState)) {
                                                WriteBankLogLn("连接服务器失败，终止本次推送");
                                                tmpRespCode = "-1";
                                                tmpRespInfo = "连接服务器失败，终止本次推送";
                                                isAllRight = false;
                                                break;
                                            } else if (ConnState.CLASS_NOT_FOUND.equals(saveResp.connState)) {
                                                WriteBankLogLn(ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送");
                                                tmpRespCode = "-1";
                                                tmpRespInfo = ConnState.CLASS_NOT_FOUND + "初始化类异常，终止本次推送";
                                                isAllRight = false;
                                                break;
                                            }
                                        }
                                        rcptDt.upFile = eachRcptMp.customFileId;
                                        retAts.writeRetDetail(rcptDt);
                                    }
                                    if (isAllRight) {
                                        FileHelper.writeFile(dataFile, receiptHtml, getCharset());
                                    }
                                } else if (eachName.toLowerCase().endsWith(".JPG")) {
                                    receiptFile.delete(); // 删除JPG
                                }
                            }

                            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
                            /*
                            int delCount = 0;
                            for (String delFile : listToDelete) {
                                try {
                                    WriteBankLogLn("删除文件" + delFile);
                                    File toDel = new File(delFile);
                                    toDel.delete();
                                    delCount++;
                                    this.WriteBankLogLnNoTime("--删除完成");
                                } catch (Exception ex) {
                                    WriteBankLogLn(ex);
                                }
                            }
                            WriteBankLogLn("成功删除了" + delCount + "个回单文件");
                            */
                            if (unknowRcptType.size() > 0) {
                                tmpRespCode = "-1";
                                tmpRespInfo = "不支持的回单类型：" + StringHelper.join(",", unknowRcptType);
                                WriteBankLogLn("不支持的回单类型：" + StringHelper.join(",", unknowRcptType));
                            }

                            for (File receiptFile : receiptFiles) {
                                if (receiptFile.isFile()) {
                                    receiptFile.delete(); // 删除HTML文件
                                }
                                if (receiptFile.isDirectory()) {
                                    receiptFile.delete(); // 删除账号目录
                                }
                            }
                            if (receiptDir.exists()) {
                                receiptDir.delete(); // 删除日期目录
                            }

                            retAts.respCode = tmpRespCode;
                            retAts.respInfo = tmpRespInfo;
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "不存在回单目录:" + receiptDir.getName();
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "下载文件失败：";
                        if (tmpReceiver != null) {
                            retAts.respInfo += tmpReceiver.connState + "-" + tmpReceiver.connMsg;
                        }
                    }
                }
            } else {
                retAts.respCode = "0";
                retAts.respInfo = "未找到回单下载的ftp设置";
            }
            json.append("]}");
            if (receiptUploadShared && "0".equals(retAts.respCode) && json.toString().contains("receiptCode")) {
                String[] data ;
                String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                if("nbGateway".equals(receiptPushType)) {
                    WriteBankLogLn("3.推送给网关的数据" + json.toString());
                    data= FormSubmit.receiptInfoSend(json.toString(),this);
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到网关成功,请查看数据");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到网关成功,请查看数据";
                    } else {
                        WriteBankLogLn("推送数据到网关失败");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到网关失败";
                    }
                }else{
                    WriteBankLogLn("3.推送给ATS的数据" + json.toString());
                    data = sendToATS(json.toString());
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到ATS成功,请查看数据");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    } else {
                        WriteBankLogLn("推送数据到ATS失败");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到ATS失败";
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPtClient != null) {
                ftpPtClient.disconnect();
            }
        }

        retAts.writeRetToATS();
        return retAts;
    }

    private RetAtsReceipt qryReceiptXml(ReqQryReceipt p_reqReceipt) throws Exception {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        retAts.respCode = "0";
        String uploadType=SmbFileUtil.getUploadType();
        try {
        	
        	ReceiptFileSaveHelper saveHelper = new ReceiptFileSaveHelper(this);
        	StringBuilder sbChk = new StringBuilder();
        	boolean saveHelperChked = saveHelper.checkSet(sbChk, "102");
        	
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            bnkTransCode = "DownEBill";
            //bnkPackageID = p_reqReceipt.reqBatchNo;
            //bnkfSeqno = p_reqReceipt.reqBatchNo;
            String templatePath = getBankConfig().getValueAsString("templetFile");
            String receiptFile = getBankConfig().getValueAsString("receiptFile");
            if (StringHelper.isNullOrEmpty(receiptFile)) {
                throw new RuntimeException("通过xml报文生成回单，config/portfiles/ICBC02/config.xml文件中的receiptFile生成电子回单pdf临时保存路径不得为空！");
            }
            //config文件中receiptFile节点可能会出现现场少写最后一个分隔符的情况
            if (!receiptFile.endsWith(File.separator)) {
                receiptFile += File.separator;
            }
			StringBuilder json = new StringBuilder();
            if(getBankConfig().getValueAsBool("receiptPushHasTenantId")){
                json.append("tenantId="+FGBiz.dspCenter.dspSet.tenant+"&transType=downloadreceipt&data={\"rows\":[");
            }else{
                json.append("transType=downloadreceipt&data={\"rows\":[");
            }
            int qryCount = 0;
            while (tmpIntFrom <= tmpIntTo && "0".equals(retAts.respCode)) {
                qryCount++;
                bnkPackageID = p_reqReceipt.reqHeader.transSeqID + String.valueOf(qryCount);
                if (bnkPackageID.length() > 35) {
                    bnkPackageID = bnkPackageID.substring(bnkPackageID.length() - 35, bnkPackageID.length());
                }
                bnkfSeqno = bnkPackageID;
                //int intFromStep = tmpIntFrom;
                Date fromDateStep = tmpCalendarFrom.getTime();
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));

                // 从本地文件读取对账单数据
                String filePath = getBankConfig().getValueAsString("hisTranFile");
                String formByDate = Format.Date8Format.format(fromDateStep);
                formByDate = formByDate.substring(0, 6) + File.separator + formByDate.substring(6, 8);
                if (StringHelper.isNullOrEmpty(filePath)) {
                    filePath = FGBiz.dspCenter.dspSet.dataDirPath + File.separator + "tempfile" + File.separator + "hisTranFile" + File.separator;
                }
                filePath = filePath + formByDate + File.separator + reqHeader.bankCode + File.separator + p_reqReceipt.actNum + ".txt";
                String fileContent = "";
                if (FileHelper.existFile(filePath)) {
                    fileContent = FtpUtil.getTextFromFile(filePath, getCharset());
                }
                if (StringHelper.isNullOrEmpty(fileContent)) {
                    WriteBankLogLn("回单下载时未找到对应的历史明细信息：" + filePath);
                    //retAts.respCode = "0";
                    //retAts.respInfo = intFromStep + "未找到对应历史明细信息";
                    continue;
                }
                String[] fileContents = fileContent.split("\r\n");
                for (int i = 0, length = fileContents.length; i < length; i++) {
                /*
                tmpRetDetail.actNum + "|" + tmpRetDetail.tranDate + "|" + askNumber|地区号|网点号|柜员号|主机交易流水号|交易方向"
                 */
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter);
                    String[] accountInfo = fileContents[i].split("\\|");
                    String receiptFileName = p_reqReceipt.actNum + "_" + Format.Date8Format.format(fromDateStep)
                            + "_" + accountInfo[2] + ".pdf";
                    if("localhost".equals(uploadType)){
                        if (new File(StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1])  +File.separator+ receiptFileName).exists()) {
                            continue;
                        }
                    }else{
                        if (new File(FGBiz.dspCenter.dspSet.receiptShareDir + receiptFileName).exists()) {
                            continue;
                        }
                    }
                    if(accountInfo.length>3){
                    	xmlWriter.writeElementString("AreaCode", accountInfo[3]);//地区号
                    }else{
                    	xmlWriter.writeElementClosed("AreaCode");
                    }
                    if(accountInfo.length>4){
                    	xmlWriter.writeElementString("NetCode", accountInfo[4]);//网点号
                    }else{
                    	xmlWriter.writeElementClosed("NetCode");
                    }
                    if(accountInfo.length>5){
                    	xmlWriter.writeElementString("TellerNo", accountInfo[5]);//柜员号
                    }else{
                    	xmlWriter.writeElementClosed("TellerNo");
                    }
                    xmlWriter.writeElementString("WorkDate", Format.Date8Format.format(fromDateStep));//交易日期
                    if(accountInfo.length>6){
                    	xmlWriter.writeElementString("TranSerialNo", accountInfo[6]);//交易流水号
                    }else{
                    	xmlWriter.writeElementClosed("TranSerialNo");
                    }
                    xmlWriter.writeElementString("AcctNo", p_reqReceipt.actNum);//账号
                    xmlWriter.writeElementString("CurrencyType", convertCurToBank(p_reqReceipt.actCur));//币种
                    xmlWriter.writeElementString("SignTime", Format.DateTime17Format.format(new Date()));//签名时间

                    xmlWriter.writeElementClosed("ReqReserved1");//请求备用字段1
                    xmlWriter.writeElementClosed("ReqReserved2");//请求备用字段2
                    xmlWriter.writeElementClosed("ReqReserved3");//请求备用字段3
                    xmlWriter.writeElementClosed("ReqReserved4");//请求备用字段4
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndDocument();
                    String[] tmpStrRet = new String[]{"", ""};
                    WriteBankLogLn("发送银行报文：" + xmlWriter.toXmlString());
                    TimeUnit.SECONDS.sleep(1);
                    tmpStrRet = sendToBank(xmlWriter.toXmlString(), true);
                    if (0 == tmpStrRet[0].length()) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String RetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                            String RetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                            if ("0".equals(RetCode)) {
                                String PayAccount = tmpBkReader.getFirstText("/CMS/eb/out/PayAccount");
                                String RecAccount = tmpBkReader.getFirstText("/CMS/eb/out/RecAccount");
                                String EbillSerialno = tmpBkReader.getFirstText("/CMS/eb/out/EbillSerialno");
                                Map<String, String> formInfoMap = new ConcurrentHashMap<String, String>();
                                formInfoMap.put("EbillSerialno", EbillSerialno);
                                formInfoMap.put("PayAccount", PayAccount);
                                formInfoMap.put("PayAcctName", tmpBkReader.getFirstText("/CMS/eb/out/PayAcctName"));
                                formInfoMap.put("PayBankName", tmpBkReader.getFirstText("/CMS/eb/out/PayBankName"));
                                formInfoMap.put("RecAccount", RecAccount);
                                formInfoMap.put("RecAcctName", tmpBkReader.getFirstText("/CMS/eb/out/RecAcctName"));
                                formInfoMap.put("RecBankName", tmpBkReader.getFirstText("/CMS/eb/out/RecBankName"));
                                String PayAmt = StringHelper.amountDivide100(tmpBkReader.getFirstText("/CMS/eb/out/PayAmt"));
                                formInfoMap.put("PayAmt", new DecimalFormat("###,##0.00").format(Double.valueOf(PayAmt)));
                                formInfoMap.put("PayAmtUp", DecimalFormat2.change2CNMoneyUnit(Double.valueOf(PayAmt)));
                                formInfoMap.put("Summary", tmpBkReader.getFirstText("/CMS/eb/out/Summary"));
                                WriteBankLogLn("备注字段值为："+tmpBkReader.getFirstText("/CMS/eb/out/Remark"));
                                formInfoMap.put("Remark", tmpBkReader.getFirstText("/CMS/eb/out/Remark"));
                                String busTypeValue = tmpBkReader.getFirstText("/CMS/eb/out/BusType");
                                String busType = getBankConfig().getMapValueByKey("receiptBusTypeMapping", busTypeValue);
                                if (StringHelper.isNullOrEmpty(busType)){
                                    formInfoMap.put("BusType", busTypeValue);
                                }else {
                                    formInfoMap.put("BusType", busType);
                                }
                                String currType = getBankConfig().getMapValueByKey("elereceiptCurMapping", tmpBkReader.getFirstText("/CMS/eb/out/CurrType"));
                                if (!StringHelper.isNullOrEmpty(currType) && currType.split(",").length == 2) {
                                    formInfoMap.put("CurrType", currType.split(",")[0]);
                                    formInfoMap.put("CurrTypeUP", currType.split(",")[1]);
                                } else {
                                    formInfoMap.put("CurrType", "CNY");
                                    formInfoMap.put("CurrTypeUP", "人民币");
                                }
                                formInfoMap.put("UseCN", tmpBkReader.getFirstText("/CMS/eb/out/UseCN"));
                                formInfoMap.put("TranSerialNo", tmpBkReader.getFirstText("/CMS/eb/out/TranSerialNo"));
                                formInfoMap.put("TimeStamp", tmpBkReader.getFirstText("/CMS/eb/out/TimeStamp"));
                                formInfoMap.put("ValueDate", Format.Date10Format.format(Format.Date10Format.parse(tmpBkReader.getFirstText("/CMS/eb/out/TimeStamp"))));
                                formInfoMap.put("EbillKey", tmpBkReader.getFirstText("/CMS/eb/out/EbillKey"));
                                formInfoMap.put("TransDate", tmpBkReader.getFirstText("/CMS/eb/out/TransDate"));
                                formInfoMap.put("GenerateDate", Format.Date10Format.format(new Date()));
                                formInfoMap.put("fSeqno", tmpBkReader.getFirstText("/CMS/eb/pub/fSeqno"));
                                formInfoMap.put("TransNetCode", tmpBkReader.getFirstText("/CMS/eb/out/TransNetCode"));
                                formInfoMap.put("TransTellno", tmpBkReader.getFirstText("/CMS/eb/out/TransTellno"));
                                formInfoMap.put("CIS", tmpBkReader.getFirstText("/CMS/eb/pub/CIS"));
                                formInfoMap.put("TranDate", Format.Date10Format.format(Format.Date8Format.parse(tmpBkReader.getFirstText("/CMS/eb/pub/TranDate"))));
                                formInfoMap.put("ID", tmpBkReader.getFirstText("/CMS/eb/pub/ID"));
                                //ATSES-20799 增加附言 业务（产品）种类
                               // formInfoMap.put("PostScript", tmpBkReader.getFirstText("/CMS/eb/out/PostScript"));
                                String postScript=tmpBkReader.getFirstText("/CMS/eb/out/PostScript");
                                if (!StringHelper.isNullOrEmpty(postScript)){
                                    formInfoMap.put("PostScript", postScript);
                                }
                                String prodType = getBankConfig().getMapValueByKey("productTypeMapping", tmpBkReader.getFirstText("/CMS/eb/out/ProdType"));
                                if (!StringHelper.isNullOrEmpty(prodType)){
                                    formInfoMap.put("ProdType", prodType);
                                }
                                String cusInfo = tmpBkReader.getFirstText("/CMS/eb/out/CusInfo");
                                if (!StringHelper.isNullOrEmpty(cusInfo)){
                                    formInfoMap.put("CusInfo", cusInfo);
                                }
                                String newPDFPath = receiptFile + receiptFileName;
                                boolean needUpload = false;
                                if (!FileHelper.existFile(newPDFPath)) {
                                    WriteBankLogLn("传入模板备注字段值为："+formInfoMap.get("Remark"));
                                    String pdfFillRet = PdfGenerateUtil.fillTemplate(templatePath, newPDFPath, formInfoMap);
                                    needUpload = "true".equals(pdfFillRet);
                                    if(!needUpload){
                                    	WriteBankLogLn("回单编号为：" + EbillSerialno+"的pdf文件生成失败："+pdfFillRet);
                                    }
                                } else {
                                    WriteBankLogLn("pdf文件已经生成过，路径为："+newPDFPath);
                                    needUpload = true;
                                }
                                if (needUpload) {
                                    //过滤掉检查配置
                                    String receiptUploadShared = this.getBankConfig().getValueAsString("receiptUploadShared");
                                    if(!StringHelper.isNullOrEmpty(receiptUploadShared) && receiptUploadShared.equals("true")){
                                        saveHelperChked = false ;
                                    }
                                	if(saveHelperChked){
                                		ReceiptMapping eachRcptMp = new ReceiptMapping();
                                    	String receiptNo = formInfoMap.get("EbillSerialno");
                                        eachRcptMp.busRef = accountInfo[2];
                                        eachRcptMp.bank = "102";
                                        eachRcptMp.setBusDate(Format.Date8Format.parse(formInfoMap.get("TransDate").replace("-", "").replace("年", "").replace("月", "").replace("日", "")));
                                        eachRcptMp.ownAct = p_reqReceipt.actNum;
                                        eachRcptMp.askNumber = "";
                                        eachRcptMp.keyName = "receiptNo";
                                        eachRcptMp.receiptNo = receiptNo;
                                        eachRcptMp.amount = new BigDecimal(formInfoMap.get("PayAmt").replace(",", ""));
                                        eachRcptMp.srcFile = receiptFileName;
                                		HelperResp saveResp = saveHelper.saveByRcptMap(reqHeader, eachRcptMp, newPDFPath);
                                        WriteBankLogLn(saveResp.sbMsg);
                                	}else{
                                        //上传文件到共享目录下
                                        int result = -1;
                                        String ftpFilePath="";
                                        String filePath2="";
                                        String AtsFilePath = "";
                                        String tmpByDate = Format.Date8Format.format(new Date());
                                        tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                        if (new File(newPDFPath).exists()) {
                                            if(!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)){
                                                if("smb".equals(uploadType)) {
                                                    WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                    result = SmbFileUtil.smbUploading(newPDFPath, tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                                    AtsFilePath = tmpByDate + receiptFileName;
                                                }else if("localhost".equals(uploadType)){
                                                    String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                                    WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                                    result = FileHelper.copyFile(newPDFPath, shareDir + tmpByDate + receiptFileName);
                                                    AtsFilePath = tmpByDate + receiptFileName;
                                                }  else{
                                                    tmpByDate =tmpByDate.replaceAll(reqHeader.bankCode + "/","");
                                                    WriteBankLogLn("正在上传文件至微服务:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                    Map<String,String> map = FormSubmit.fileUpload
                                                            (FGBiz.dspCenter.dspSet.receiptShareDir,p_reqReceipt.actNum,newPDFPath,tmpByDate,receiptFileName,getCharset());
                                                    WriteBankLogStep3(JSON.toJSONString(map));
                                                    if(map.keySet().size()!=0){
                                                        result = Integer.valueOf(map.get("respCode"));
                                                        tmpByDate =map.get("remotePath");
                                                        AtsFilePath = tmpByDate;
                                                    }else{
                                                        result = -1;
                                                    }
                                                }
                                            }else {
                                                //ftp服务器
                                                FtpSet ftpSet = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet.upDir);
                                                //上传ftp服务器的地址
                                                filePath2=tmpByDate+receiptFileName;
                                                ftpFilePath = StringHelper.trimEndFileSp(ftpSet.upDir) + "/" +filePath2;
                                                WriteBankLogLn("开始将回单"+newPDFPath+"上传至"+ftpFilePath);
                                                //上传至ftp
                                                result = FtpUtil.ftpUploading(ftpSet, newPDFPath, ftpFilePath);
                                                AtsFilePath = filePath2;
                                            }
                                        }
                                        if (result == 0 || result == 1) {
                                            if (result == 0){
                                                WriteBankLogLn("文件上传成功");
                                            }else {
                                                WriteBankLogLn("文件已存在共享目录无需重复上传");
                                            }
                                            if (FileHelper.deleteFileIfExists(newPDFPath)) {
                                                WriteBankLogLn("已删除临时文件：" + newPDFPath);
                                            }
                                            //推送数据给ATS处理
                                            json.append("{");
                                            json.append("\"actNum\":\"" + p_reqReceipt.actNum + "\",");
                                            json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                            json.append("\"receiptCode\":\"" + formInfoMap.get("EbillSerialno") + "\",");
                                            json.append("\"receiptType\":\"" + "" + "\",");
                                            json.append("\"receiptState\":\"" + "" + "\",");
                                            if (!p_reqReceipt.actNum.equals(PayAccount)) {
                                                json.append("\"oppActName\":\"" + formInfoMap.get("PayAcctName") + "\",");
                                                json.append("\"oppActNum\":\"" + PayAccount + "\",");
                                                json.append("\"moneyway\":\"" + "2" + "\",");
                                            } else {
                                                json.append("\"oppActName\":\"" + formInfoMap.get("RecAcctName") + "\",");
                                                json.append("\"oppActNum\":\"" + RecAccount + "\",");
                                                json.append("\"moneyway\":\"" + "1" + "\",");
                                            }
                                            json.append("\"amount\":\"" + formInfoMap.get("PayAmt").replace(",", "") + "\",");
                                            json.append("\"tranSeqNo\":\"" + accountInfo[2] + "\",");
                                            json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                            json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(formInfoMap.get("TransDate").replace("-", "").replace("年", "").replace("月", "").replace("日", ""))) + "\",");
                                            json.append("\"filePath\":\"" + AtsFilePath + "\",");//文件路径
                                            json.append("\"fileType\":\"1\"");
                                            json.append("},");
                                        } else {
                                            retAts.respCode = "-1";
                                            retAts.respInfo = "上传文件至共享目录失败，请检查共享目录配置是否正确";
                                            break;
                                            //WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                        }
                                	}
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = "pdf文件失败，对应回单编号为：" + EbillSerialno;
                                    break;
                                    //WriteBankLogLn("生成pdf文件失败");
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = Format.Date8Format.format(fromDateStep) + "下载失败：" + RetMsg;
                                break;
                                //WriteBankLogLn(RetMsg);
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = Format.Date8Format.format(fromDateStep) + "下载失败：" + tmpSbMsg.toString();
                            break;
                            //WriteBankLogLn(tmpSbMsg.toString());
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = Format.Date8Format.format(fromDateStep) + "下载失败：" + tmpStrRet[1];
                        break;
                        //WriteBankLogLn(tmpStrRet[1]);
                    }
                }
            }
            if(saveHelperChked == false){
            json.deleteCharAt(json.length() - 1);
            json.append("]}");
            if ("0".equals(retAts.respCode) && json.toString().contains("receiptCode")) {
                String[] data ;
                String receiptPushType = FGBiz.dspCenter.dspSet.receiptPushType;
                if("nbGateway".equals(receiptPushType)) {
                    WriteBankLogLn("3.推送给网关的数据" + json.toString());
                    data= FormSubmit.receiptInfoSend(json.toString(),this);
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到网关成功,请查看数据");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到网关成功,请查看数据";
                    } else {
                        WriteBankLogLn("推送数据到网关失败");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到网关失败";
                    }
                }else{
                    WriteBankLogLn("3.推送给ATS的数据" + json.toString());
                    data = sendToATS(json.toString());
                    if (data[0].length() == 0 && data[1].equals("ok")) {
                        WriteBankLogLn("推送数据到ATS成功,请查看数据");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    } else {
                        WriteBankLogLn("推送数据到ATS失败");
                        retAts.respCode = "0";
                        retAts.respInfo = "推送数据到ATS失败";
                    }
                }
            }
            }
        } catch (Exception ex) {
            //ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetToATS();
        return retAts;
    }
}
